package com.qf.realm;


import com.qf.domain.SysUsers;
import com.qf.service.MenuService;
import com.qf.service.RoleService;
import com.qf.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author 千峰教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class MyUserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
@Autowired
RoleService roleService;
@Autowired
MenuService menuService;

    //提供授权信息（权限）
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) 		{
        SysUsers  sysUsers = (SysUsers) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        Set<String> roles=roleService.findRoles(sysUsers.getId());
        Set<String> perms=menuService.findPerms(sysUsers.getId());
        //需要角色信息
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(perms);
        return authorizationInfo;
    }


    //提供认证信息（账号和密码）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username= (String) token.getPrincipal();
        String password=new String((char[])token.getCredentials());
        SysUsers sysUsers = userService.findByUsername(username);

        if(sysUsers==null){
            throw new UnknownAccountException("未知的账户信息");
        }
        if (sysUsers.getStatus()==0){
            throw new LockedAccountException("账户已锁定");
        }
        if (!password.equals(sysUsers.getPassword())){
            throw new CredentialsException("密码错误");
        }

        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(sysUsers,password,sysUsers.getRealname());
        return authenticationInfo;
    }
}
